﻿namespace QuickMail.View.Windows
{
    using System.Windows;

    using QuickMail.BusinessLogic;
    using QuickMail.DataModels;
    using QuickMail.View.Controls;
    using QuickMail.Properties;

    /// <summary>
    /// Window settings for connecting to the mail.
    /// </summary>
    public partial class ConnectSettingsWindow
    {
        #region Fields

        private enum StateEnum
        {
            Standart = 0,
            Extention = 1,
            Wait = 2,
            Success = 3,
        }

        private readonly StandartConnectSettings _scs = new StandartConnectSettings();
        private readonly ExtendedConnectSettings _ecs;
        private readonly WaitConnect _waitConnect = new WaitConnect();
        private readonly SuccessConnect _successConnect = new SuccessConnect();

        private readonly TestConnectionController _tcController;

        private StateEnum _currentState;

        #endregion //End fields

        public ConnectSettingsWindow(TestConnectionController tcController)
        {
            InitializeComponent();

            // ReSharper disable once RedundantThisQualifier
            this.Title = StaticFields.Lang.ConnectSettingsWindow.Title;
            SwitchModeButton.Content = StaticFields.Lang.ConnectSettingsWindow.ExtendedSetup;
            AcceptButton.Content = StaticFields.Lang.ConnectSettingsWindow.Next;
            CancelButton.Content = StaticFields.Lang.ConnectSettingsWindow.Cancel;

            _tcController = tcController;
            _ecs = new ExtendedConnectSettings(tcController);
            SwitchToStandartMode();
        }

        #region Interface events

        /// <summary>
        /// Click on next/apply/finish
        /// </summary>
        private void Accept_OnClick(object sender, RoutedEventArgs e)
        {
            switch (_currentState)
            {
                case StateEnum.Standart:
                    SwitchToWaitConnect();
                    break;
                case StateEnum.Success:
                    DialogResult = true;
                    break;
                case StateEnum.Extention:
                    ExtendedApplySettings();
                    break;
            }
        }

        /// <summary>
        /// Standart/Extension setup on click
        /// </summary>
        private void ChangeType_OnClick(object sender, RoutedEventArgs e)
        {
            switch (_currentState)
            {
                case StateEnum.Standart:
                case StateEnum.Wait:
                case StateEnum.Success:
                    SwitchToExtendedMode();
                    break;
                case StateEnum.Extention:
                    SwitchToStandartMode();
                    break;
            }
        }

        /// <summary>
        /// Switch to  standart mode.
        /// </summary>
        private void SwitchToStandartMode()
        {
            SwitchModeButton.Content = StaticFields.Lang.ConnectSettingsWindow.ExtendedSetup;
            AcceptButton.Content = StaticFields.Lang.ConnectSettingsWindow.Next;

            _scs.LoadSettings();
            ConnectContentPresenter.Content = _scs;
            _currentState = StateEnum.Standart;
        }

        /// <summary>
        /// Switch to extended mode.
        /// </summary>
        private void SwitchToExtendedMode()
        {
            if (string.IsNullOrEmpty(Settings.Default.GetEmail)
                || string.IsNullOrEmpty(Settings.Default.GetServer)
                || string.IsNullOrEmpty(Settings.Default.SendEmail)
                || string.IsNullOrEmpty(Settings.Default.SendServer))
            {
                if (_scs.CheckingFields())
                {
                    //ConnectionSetupWorker.DetectServer
                    //    (_scs.FullNameTextBox.Text.Trim(), _scs.EmailTextBox.Text.Trim(), _scs.UserPasswordBox.Password);
                    ConnectionSetupWorker.DetectServer
                        (string.Empty, _scs.EmailTextBox.Text.Trim(), _scs.UserPasswordBox.Password);
                }
            }

            SwitchModeButton.Content = StaticFields.Lang.ConnectSettingsWindow.StandartSetup;
            AcceptButton.Content = StaticFields.Lang.ConnectSettingsWindow.Apply;

            _ecs.LoadSettings();
            ConnectContentPresenter.Content = _ecs;
            _currentState = StateEnum.Extention;
        }

        /// <summary>
        /// Switch to  wait connect.
        /// </summary>
        private void SwitchToWaitConnect()
        {
            if (!_scs.CheckingFields())
                return;

            ConnectContentPresenter.Content = _waitConnect;
            _currentState = StateEnum.Wait;
            _tcController.TestConnectionComplete += OnTestConnectionComplete;

            //if (ConnectionSetupWorker.DetectServer
            //    (_scs.FullNameTextBox.Text.Trim(), _scs.EmailTextBox.Text.Trim(), _scs.UserPasswordBox.Password))
                if (ConnectionSetupWorker.DetectServer
                    (string.Empty, _scs.EmailTextBox.Text.Trim(), _scs.UserPasswordBox.Password))
            {
                _tcController.RunTestConntection();
            }
            else
            {
                //TODO make autoconfiguration
                _tcController.RunTestConntection();
            }
        }

        /// <summary>
        /// Switches control when received the answer.
        /// </summary>
        private void OnTestConnectionComplete(bool incomingResult, bool outgoingResult)
        {
            _tcController.TestConnectionComplete -= OnTestConnectionComplete;

            if (incomingResult && outgoingResult)
            {
                SwitchToSuccessConnect();
            }
            else
            {
                SwitchToExtendedMode();
                _ecs.ShowIncomingStatus(incomingResult);
                _ecs.ShowOutgoingStatus(outgoingResult);
            }
        }

        /// <summary>
        /// Switches to the successful connection setup window.
        /// </summary>
        private void SwitchToSuccessConnect()
        {
            AcceptButton.Content = StaticFields.Lang.ConnectSettingsWindow.Finish;
            ConnectContentPresenter.Content = _successConnect;
            _currentState = StateEnum.Success;
        }

        /// <summary>
        /// Saves the extended settings.
        /// </summary>
        private void ExtendedApplySettings()
        {
            if (!_ecs.CheckingFields())
                return;

            _ecs.SaveSettings();
            DialogResult = true;
        }

        #endregion //End Interface events
    }
}
